﻿using System;
using System.ComponentModel;
using System.Windows;
using InfiniTec;

namespace CalendarSubscriptionApp
{
	public sealed class AppointmentsWindowViewModel : INotifyPropertyChanged
	{
		private readonly SubscriptionManagerViewModel _ViewModel;
		private string _NewMailboxAddress;

		public AppointmentsWindowViewModel(SubscriptionManagerViewModel viewModel)
		{
			if (viewModel == null) throw new ArgumentNullException("viewModel");

			_ViewModel = viewModel;
		}

		public SubscriptionManagerViewModel ViewModel
		{
			get { return _ViewModel; }
		}

		public string NewMailboxAddress
		{
			get { return _NewMailboxAddress; }
			set
			{
				if (value == _NewMailboxAddress) return;
				_NewMailboxAddress = value;
				PropertyChanged.Raise(this, "NewMailboxAddress");
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		#endregion

		public void ShowAppointmentsWindow()
		{
			var dialog = new AppointmentsWindow(this);
			dialog.Show();
		}

		public void OpenMailbox()
		{
			if (NewMailboxAddress.IsNullOrEmpty())
			{
				MessageBox.Show("The email address must not be empty", "Error");
				return;
			}
			try
			{
				_ViewModel.SubscribeToCalendar(NewMailboxAddress);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Subscription failed", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			NewMailboxAddress = string.Empty;
		}
	}
}